﻿#pragma execution_character_set("utf-8")

#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QCryptographicHash>

#include "requests.h"
#include "login.h"
#include "ui_login.h"
#include "appconfig.h"

Login::Login(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Login)
{
    ui->setupUi(this);

    Qt::CheckState state = (Qt::CheckState)CFGAPP->isRemainPassword();
    ui->box_remain_passwd->setCheckState(state);
    ui->edit_user->setText(CFGAPP->userName());
    if(Qt::CheckState::Checked  == state)
        ui->edit_password->setText(CFGAPP->userPassword());
}

Login::~Login()
{
    delete ui;
}

void Login::on_btn_register_clicked()
{
    m_registerPage.exec();
}


void Login::on_btn_login_clicked()
{
    auto user = ui->edit_user->text();
    auto passwd = ui->edit_password->text();
    QString passwd_md5 = QCryptographicHash::hash(passwd.toLocal8Bit(), QCryptographicHash::Md5);
    qInfo() << passwd_md5 << passwd_md5.length();
    if(user.isEmpty()) {
        QMessageBox::warning(this, "警告", "用户名不能为空");
        return;
    }
    if(passwd.isEmpty()) {
        QMessageBox::warning(this, "警告", "密码不能为空");
        return;
    }


    auto date = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QJsonObject obj = {{"user", user}, {"password", passwd_md5}};
    auto str = QJsonDocument(obj).toJson(QJsonDocument::Compact).toBase64().toStdString();
    auto resp = requests::post("192.168.2.138:8080/login", str.c_str());
    if (resp == NULL) {
        qInfo() << "request failed!\n";
    }
    else {
        auto str = QByteArray::fromBase64(resp->body.c_str());
        qInfo() << str;
        QJsonObject respObj = QJsonDocument::fromJson(str).object();
        if(respObj.contains("result") && respObj["result"].toBool()) {
            emit accept();
        }
        else {
            QMessageBox::warning(this, "警告", "登录失败");
        }
    }
}


void Login::on_box_remain_passwd_stateChanged(int arg1)
{
    CFGAPP->remainPassword(arg1);
}


void Login::on_edit_user_editingFinished()
{
    CFGAPP->setUserName(ui->edit_user->text());
}


void Login::on_edit_password_editingFinished()
{
    Qt::CheckState state = (Qt::CheckState)CFGAPP->isRemainPassword();
    if(Qt::CheckState::Checked  == state) {
        CFGAPP->setUserPassword(ui->edit_password->text());
    }
    else {
        CFGAPP->setUserPassword("");
    }
}


void Login::on_box_choose_stateChanged(int arg1)
{
    CFGAPP->remainCustom(arg1);
}

